package com.evan.review.ipc;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 笔记内容提供者
 * 用于演示ContentProvider的跨进程数据共享功能
 */
public class NoteProvider extends ContentProvider {
    private static final String TAG = "NoteProvider";

    // 数据库帮助类
    private DatabaseHelper dbHelper;
    // 数据库实例
    private SQLiteDatabase database;

    // URI相关常量
    private static final String AUTHORITY = "com.evan.review.provider";
    private static final String PATH_NOTES = "notes";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH_NOTES);

    // UriMatcher实例，用于匹配Uri
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    // 匹配码
    private static final int CODE_NOTES = 1;
    private static final int CODE_NOTE_ITEM = 2;

    // 设置Uri匹配规则
    static {
        // 匹配整个笔记表的Uri
        uriMatcher.addURI(AUTHORITY, PATH_NOTES, CODE_NOTES);
        // 匹配单个笔记项的Uri（带ID）
        uriMatcher.addURI(AUTHORITY, PATH_NOTES + "/#", CODE_NOTE_ITEM);
    }

    // 数据库和表定义
    private static final String DATABASE_NAME = "notes.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NOTES = "notes";

    // 表字段
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_CONTENT = "content";
    public static final String COLUMN_TIMESTAMP = "timestamp";

    // 创建表SQL语句
    private static final String SQL_CREATE_NOTES_TABLE =
            "CREATE TABLE " + TABLE_NOTES + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_TITLE + " TEXT NOT NULL, " +
                    COLUMN_CONTENT + " TEXT, " +
                    COLUMN_TIMESTAMP + " INTEGER)";

    /**
     * 数据库帮助类
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(SQL_CREATE_NOTES_TABLE);
            Log.d(TAG, "数据库创建成功");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // 简单版本升级处理 - 生产环境中应该更复杂一些
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
            onCreate(db);
        }
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        if (context != null) {
            dbHelper = new DatabaseHelper(context);
            database = dbHelper.getWritableDatabase();
            return true;
        }
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,
                        @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        // 获取可读数据库
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor;

        // 根据Uri类型执行不同的查询
        switch (uriMatcher.match(uri)) {
            case CODE_NOTES:
                // 查询整个笔记表
                cursor = db.query(TABLE_NOTES, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case CODE_NOTE_ITEM:
                // 查询单个笔记项
                selection = COLUMN_ID + "=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                cursor = db.query(TABLE_NOTES, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }

        // 设置内容变化通知
        if (getContext() != null) {
            cursor.setNotificationUri(getContext().getContentResolver(), uri);
        }

        return cursor;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (uriMatcher.match(uri)) {
            case CODE_NOTES:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_NOTES;
            case CODE_NOTE_ITEM:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_NOTES;
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        // 只支持对整个表的插入
        if (uriMatcher.match(uri) != CODE_NOTES) {
            throw new IllegalArgumentException("不支持该URI的插入操作: " + uri);
        }

        // 执行数据库插入
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long id = db.insert(TABLE_NOTES, null, values);

        // 插入失败
        if (id == -1) {
            Log.e(TAG, "插入笔记失败: " + uri);
            return null;
        }

        // 通知数据变化
        if (getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        // 返回包含新记录ID的URI
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;

        switch (uriMatcher.match(uri)) {
            case CODE_NOTES:
                // 删除整个表或按条件删除
                count = db.delete(TABLE_NOTES, selection, selectionArgs);
                break;
            case CODE_NOTE_ITEM:
                // 删除单个笔记项
                selection = COLUMN_ID + "=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                count = db.delete(TABLE_NOTES, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }

        // 通知数据变化
        if (count > 0 && getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection,
                      @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;

        switch (uriMatcher.match(uri)) {
            case CODE_NOTES:
                // 更新整个表或按条件更新
                count = db.update(TABLE_NOTES, values, selection, selectionArgs);
                break;
            case CODE_NOTE_ITEM:
                // 更新单个笔记项
                selection = COLUMN_ID + "=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                count = db.update(TABLE_NOTES, values, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }

        // 通知数据变化
        if (count > 0 && getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return count;
    }
} 